package com.goods.controller;

import cn.itcast.commons.CommonUtils;
import com.goods.pojo.Book;
import com.goods.pojo.Category;
import com.goods.pojo.Page;
import com.goods.service.BookService;
import com.goods.service.CategoryService;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.*;
import java.awt.*;
import java.io.File;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/admin/AdminBookController")
public class AdminBookController {
	
	@Resource
	private BookService bookServiceImpl;
	@Resource
	private CategoryService  categoryServiceImpl;

	
	/**
	 * 显示所有分类
	 */
	@RequestMapping("/findCategoryAll")
	public String findCategoryAll(HttpServletRequest req, HttpServletResponse resp){
		List<Category> parents = categoryServiceImpl.findAll();
		req.setAttribute("parents", parents);
		return "/adminjsps/admin/book/left.jsp";
	}
	
	
	/**
	 * 获取当前页码
	 * @param req
	 * @return
	 */
	private int getPc(HttpServletRequest req) {
		int pc = 1;
		String param = req.getParameter("pc");
		if(param != null && !param.trim().isEmpty()) {
			try {
				pc = Integer.parseInt(param);
			} catch(RuntimeException e) {}
		}
		return pc;
	}

	// 截取url，分页导航中使用它做为超链接的目标
	/*
	 * http://localhost:8080/goods/BookController/findByCategory?cid=xxx&pc=3
	 * /goods/BookController/findByCategory + cid=xxx&pc=3
	 */
	private String getUrl(HttpServletRequest req) {
		String url = req.getRequestURI() + "?" + req.getQueryString();
		///goods/BookController/findByCategory?cid=5F79D0D246AD4216AC04E9C5FAB3199E++++++++++++++++++++++++++++
		/*如果url中存在pc参数，就截取掉，否则截取。
		 * 	lastIndexOf : 从右到左，字符串出现的最后一次位置
		 *  */
		int index = url.lastIndexOf("&pc=");
		if(index != -1) {
			// 截取字符串 索引 0 - index
			url = url.substring(0, index);
		}
		return url;
	}
	
	// 按分类查
	@RequestMapping(value = "/findByCategory")
	public String findByCategory(HttpServletRequest req, HttpServletResponse resp){
		int pc = getPc(req);
		String url = getUrl(req);
		String cid = req.getParameter("cid");
		Page<Book> pb = bookServiceImpl.findByCategory(cid, pc);
		pb.setUrl(url);
		req.setAttribute("pb", pb);
		return "/adminjsps/admin/book/list.jsp";
	}
	
	// 按作者查
	@RequestMapping(value = "/findByAuthor")
	public String findByAuthor(HttpServletRequest req, HttpServletResponse resp){
		int pc = getPc(req);
		String url = getUrl(req);
		String author = req.getParameter("author");
		Page<Book> pb = bookServiceImpl.findByAuthor(author, pc);
		// 给Page设置url，保存Page
		pb.setUrl(url);
		req.setAttribute("pb", pb);
		return "/adminjsps/admin/book/list.jsp";
	}
	

	// 按出版社查询
	@RequestMapping(value = "/findByPress")
	public String findByPress(HttpServletRequest req, HttpServletResponse resp){
		int pc = getPc(req);
		String url = getUrl(req);
		String press = req.getParameter("press");
		Page<Book> pb = bookServiceImpl.findByPress(press, pc);
		// 给Page设置url，保存Page
		pb.setUrl(url);
		req.setAttribute("pb", pb);
		return "/adminjsps/admin/book/list.jsp";
	}
	

	 // 按图名查
	@RequestMapping(value = "/findByBname")
	public String findByBname(HttpServletRequest req, HttpServletResponse resp){
		int pc = getPc(req);
		String url = getUrl(req);
		String bname = req.getParameter("bname");
		Page<Book> pb = bookServiceImpl.findByBname(bname, pc);
		// 给Page设置url，保存Page
		pb.setUrl(url);
		req.setAttribute("pb", pb);
		return "/adminjsps/admin/book/list.jsp";
	}

	// 多条件组合查询
	@RequestMapping(value = "/findByCombination")
	public String findByCombination(Book book,HttpServletRequest req, HttpServletResponse resp){
		int pc = getPc(req);
		String url = getUrl(req);
		Page<Book> pb = bookServiceImpl.findByCombination(book, pc);
		// 给Page设置url，保存Page
		pb.setUrl(url);
		req.setAttribute("pb", pb);
		return "/adminjsps/admin/book/list.jsp";
	}
	
	
	// 查询一本书的详细信息,按bid查询
	@RequestMapping(value = "/load")
	public String load(HttpServletRequest req, HttpServletResponse resp){
		String bid = req.getParameter("bid");//获取链接的参数bid
		Book book = bookServiceImpl.findByBid(bid);
		req.setAttribute("book", book);
		// 获取所有一级分类
		req.setAttribute("parents", categoryServiceImpl.findParents());
		// 获取一级分类下所有2级分类
		String pid = book.getCategory().getPid();
		// System.out.println(pid+"===========================");
		List<Category> category = categoryServiceImpl.findChildren(pid);
		req.setAttribute("children", category);
		return "/adminjsps/admin/book/desc.jsp";
	}

	// 添加图书：第一步
	@RequestMapping(value = "/addPre")
	public String addPre(HttpServletRequest req, HttpServletResponse resp){
		// 获取所有一级分类
		List<Category> parents = categoryServiceImpl.findParents();
		req.setAttribute("parents", parents);
		return "/adminjsps/admin/book/add.jsp";
	}

	@RequestMapping(value = "/ajaxFindChildren")
	@ResponseBody
	public List<Category> ajaxFindChildren(HttpServletRequest req, HttpServletResponse resp){
		// 通过pid查询出所有2级分类
		String pid = req.getParameter("pid");
		List<Category> children = categoryServiceImpl.findChildren(pid);
		return children;
	}

	// 添加图书
	@RequestMapping(value = "/addBook")
	public String addBook(Book book,HttpServletRequest req, HttpServletResponse resp) throws UnsupportedEncodingException{
		System.out.println("===================="+book);
		/*
		 * 1. commons-fileupload的上传三步
		 */
		// 创建工具
		FileItemFactory factory = new DiskFileItemFactory();
		/*
		 * 2. 创建解析器对象
		 */
		ServletFileUpload sfu = new ServletFileUpload(factory);
		sfu.setFileSizeMax(80 * 1024);//设置单个上传的文件上限为80KB
		/*
		 * 3. 解析request得到List<FileItem>
		 */
		List<FileItem> fileItemList = null;
		try {
			fileItemList = sfu.parseRequest(req);
		} catch (FileUploadException e) {
			// 如果出现这个异步，说明单个文件超出了80KB
			req.setAttribute("msg", "上传的文件超出了80KB");
			req.setAttribute("parents", categoryServiceImpl.findParents());//所有一级分类
			return "/adminjsps/msg.jsp";
		}
		
		/*
		 * 4. 把List<FileItem>封装到Book对象中
		 * 4.1 首先把“普通表单字段”放到一个Map中，再把Map转换成Book和Category对象，再建立两者的关系
		 */
		
		Map<String,Object> map = new HashMap<String,Object>();
		for(FileItem fileItem : fileItemList) {
			if(fileItem.isFormField()) {//如果是普通表单字段
				map.put(fileItem.getFieldName(), fileItem.getString("UTF-8"));
				System.out.println("---------"+fileItem.getFieldName()+"----------");
			}
		}
		// 将map转换成book对象
		book.setAuthor(map.get("author").toString());
		book.setBname(map.get("bname").toString());
		book.setBooksize(Integer.parseInt(map.get("booksize").toString()));
		book.setCid( map.get("cid").toString());
		book.setCurrPrice(Double.parseDouble(map.get("currPrice").toString()));
		book.setDiscount(Double.parseDouble(map.get("discount").toString()));
		book.setEdition(Integer.parseInt(map.get("edition").toString()));
		book.setPageNum(Integer.parseInt(map.get("pageNum").toString()));
		book.setPaper(map.get("paper").toString());
		book.setPress(map.get("press").toString());
		book.setPrice(Double.parseDouble(map.get("booksize").toString()));
		book.setPrinttime(map.get("printtime").toString());
		book.setPublishtime(map.get("publishtime").toString());
		book.setWordNum(Integer.parseInt(map.get("wordNum").toString()));
		System.out.println("===================="+book+"=====================");
		book.setCategory(bookServiceImpl.findCategoryByCid(book.getCid()));
		/*
		 * 4.2 把上传的图片保存起来
		 *   > 获取文件名：并截取
		 *   > 给文件添加前缀：使用uuid前缀，为也避免文件同名现象
		 *   > 校验文件的扩展名：只能是jpg
		 *   > 校验图片的尺寸
		 *   > 指定图片的保存路径，使用ServletContext#getRealPath()
		 *   > 保存
		 *   > 把图片的路径设置给Book对象
		 */
		// 获取文件名
		FileItem fileItem = fileItemList.get(1);//获取大图
		String filename = fileItem.getName();
		// 截取文件名，除去浏览器上传的绝对路径
		int index = filename.lastIndexOf("\\");
		if(index != -1) {
			filename = filename.substring(index + 1);
		}
		// 给文件名添加前缀，避免重名
		filename = CommonUtils.uuid() + "_" + filename;
		// 校验文件名称的扩展名
		if(!filename.toLowerCase().endsWith(".jpg")) {
			req.setAttribute("msg", "上传的图片扩展名必须是JPG");
			req.setAttribute("parents", categoryServiceImpl.findParents());//所有一级分类
			return "/adminjsps/msg.jsp";
		}
		// 校验图片的尺寸
		// 保存上传的图片，把图片new成图片对象：Image、Icon、ImageIcon、BufferedImage、ImageIO
		/*
		 * 保存图片：
		 * 1. 获取真实路径
		 */
		String savepath = req.getSession().getServletContext().getRealPath("/book_img");
		System.out.println(savepath+"................................");
		/*
		 * 2. 创建目标文件
		 */
		File destFile = new File(savepath, filename);
		/*
		 * 3. 保存文件
		 */
		try {
			fileItem.write(destFile);//它会把临时文件重定向到指定的路径，再删除临时文件
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		
		// 校验尺寸
		// 1. 使用文件路径创建ImageIcon
		ImageIcon icon = new ImageIcon(destFile.getAbsolutePath());
		// 2. 通过ImageIcon得到Image对象
		Image image = icon.getImage();
		// 3. 获取宽高来进行校验
		if(image.getWidth(null) > 350 || image.getHeight(null) > 350) {
			req.setAttribute("msg", "您上传的图片尺寸超出了350*350！");
			//所有一级分类
			req.setAttribute("parents", categoryServiceImpl.findParents());
			destFile.delete();//删除图片
			return "/adminjsps/msg.jsp";
			
		}
		
		// 把图片的路径设置给book对象
		book.setImage_w("book_img/" + filename);

		// 获取文件名
		fileItem = fileItemList.get(2);//获取小图
		filename = fileItem.getName();
		// 截取文件名，除去浏览器上传的绝对路径
		index = filename.lastIndexOf("\\");
		if(index != -1) {
			filename = filename.substring(index + 1);
		}
		// 给文件名添加前缀，避免文件同名现象
		filename = CommonUtils.uuid() + "_" + filename;
		// 校验文件名称的扩展名
		if(!filename.toLowerCase().endsWith(".jpg")) {
			req.setAttribute("msg", "上传的图片扩展名必须是JPG");
			req.setAttribute("parents", categoryServiceImpl.findParents());//所有一级分类
			return "/adminjsps/msg.jsp";
		}
		// 校验图片的尺寸
		// 保存上传的图片，把图片new成图片对象：Image、Icon、ImageIcon、BufferedImage、ImageIO
		/*
		 * 保存图片：
		 * 1. 获取真实路径
		 */
		savepath = req.getSession().getServletContext().getRealPath("/book_img");
		System.out.println(savepath+".............................");
		/*
		 * 2. 创建目标文件
		 */
		destFile = new File(savepath, filename);
		/*
		 * 3. 保存文件
		 */
		try {
			fileItem.write(destFile);//它会把临时文件重定向到指定的路径，再删除临时文件
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		// 校验尺寸
		// 1. 使用文件路径创建ImageIcon
		icon = new ImageIcon(destFile.getAbsolutePath());
		// 2. 通过ImageIcon得到Image对象
		image = icon.getImage();
		// 3. 获取宽高来进行校验
		if(image.getWidth(null) > 350 || image.getHeight(null) > 350) {			
			req.setAttribute("msg", "您上传的图片尺寸超出了350*350！");
			req.setAttribute("parents", categoryServiceImpl.findParents());//所有一级分类
			destFile.delete();//删除图片
			return "/adminjsps/msg.jsp";
		}
		
		// 把图片的路径设置给book对象
		book.setImage_b("book_img/" + filename);

		// 调用service完成保存
		book.setBid(CommonUtils.uuid());
		int index1 = bookServiceImpl.add(book);
		// 保存成功信息转发到msg.jsp
		req.setAttribute("msg", "添加图书成功！");
		return "/adminjsps/msg.jsp";
	}

	// 删除图书
	@RequestMapping(value = "/deleteBook")
	public String delete(HttpServletRequest req, HttpServletResponse resp){
		String bid = req.getParameter("bid");
		Book book = bookServiceImpl.findByBid(bid);
		String savepath = req.getSession().getServletContext().getRealPath("/");//获取真实的路径
		// 删除图片
		new File(savepath, book.getImage_w()).delete();
		new File(savepath, book.getImage_b()).delete();
		// 删除数据库信息
		int index = bookServiceImpl.delete(bid);
		req.setAttribute("msg", "删除图书成功！");
		return "/adminjsps/msg.jsp";
	}
	
	// 修改图书
	@RequestMapping(value = "/edit")
	public String edit(Book book,HttpServletRequest req, HttpServletResponse resp){
		book.setCategory(bookServiceImpl.findCategoryByCid(book.getCid()));
		int index = bookServiceImpl.edit(book);
		req.setAttribute("msg", "修改图书成功！");
		return "/adminjsps/msg.jsp";
	}
	
}
